﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Common.Exceptions;
using Data.Common;
using Data.Contracts.ApplicationModels;
using Data.Contracts.Models;

namespace MockImplementation
{
    internal class MockUsersApplicationModel : MockBaseApplicationModel, IUsersApplicationModel
    {
        private readonly ObservableCollection<IUser> _tempUserCollection = new ObservableCollection<IUser>();

        public MockUsersApplicationModel()
        {
            GenerateUsers();
        }

        private void GenerateUsers()
        {
            BaseUser user1 = new BaseUser(Guid.NewGuid());
            user1.Username = "Shahar";
            user1.Password = "CodePlex";
            user1.Email = "shahare@live.com";
            _tempUserCollection.Add(user1);
            BaseUser user2 = new BaseUser(Guid.NewGuid());
            user2.Username = "Eldad";
            user2.Password = "CodePlex";
            user2.Email = "shahare@live.com";
            _tempUserCollection.Add(user2);
        }

        public Task<IEnumerable<IUser>> GetAllUsers()
        {
            return Task.Factory.StartNew(() => _tempUserCollection.AsEnumerable());
        }

        public IUser CreateUser()
        {
            return new BaseUser(Guid.NewGuid());
        }

        public Task UpdateUser(IUser user)
        {
            return Task.Factory.StartNew(() =>
            {
                IUser originalUser = _tempUserCollection.FirstOrDefault(u => u.Id == user.Id);
                if (originalUser != null)
                {
                    if (!TryCopyModel(user, out originalUser))
                        throw new OperationFailedException(string.Format("Failed to update user '{0}'", user.Name));
                }
            });
        }

        public Task DeleteUser(Guid userId)
        {
            return Task.Factory.StartNew(() =>
            {
                IUser originalUser = _tempUserCollection.FirstOrDefault(u => u.Id == userId);
                if (originalUser != null)
                {
                    _tempUserCollection.Remove(originalUser);
                }
            });
        }
    }
}
